package com.iteaj.iot.server.udp;

import com.iteaj.iot.ConcurrentStorageManager;
import com.iteaj.iot.Protocol;
import com.iteaj.iot.SocketDeviceManager;
import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.DatagramChannel;

import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public class UdpDeviceManager extends ConcurrentStorageManager<String, UdpIdleState> implements SocketDeviceManager<UdpIdleState> {

    private DatagramChannel channel;

    @Override
    public int useSize() {
        return size();
    }

    @Override
    public Collection<UdpIdleState> devices() {
        return Collections.unmodifiableCollection(this.getStorage().values());
    }

    @Override
    public UdpIdleState find(String equipCode) {
        return equipCode == null ? null : get(equipCode);
    }

    @Override
    public boolean close(String equipCode) {
        if(equipCode != null) {
            remove(equipCode); return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isClose(String equipCode) {
        return isExists(equipCode);
    }

    @Override
    public UdpIdleState add(String equipCode, UdpIdleState device) {
        return equipCode != null ? super.add(equipCode, device) : null;
    }

    @Override
    public UdpIdleState remove(String key) {
        return super.remove(key);
    }

    @Override
    public Optional<ChannelFuture> writeAndFlush(String equipCode, Object msg, Object... args) {
        ChannelFuture channelFuture = channel.writeAndFlush(msg);
        return Optional.of(channelFuture);
    }

    @Override
    public Optional<ChannelFuture> writeAndFlush(String equipCode, Protocol protocol) {
        return this.writeAndFlush(equipCode, protocol, null);
    }

    public DatagramChannel getChannel() {
        return channel;
    }

    public void setChannel(DatagramChannel channel) {
        this.channel = channel;
    }

    @Override
    public ConcurrentHashMap getStorage() {
        throw new UnsupportedOperationException("不支持的操作");
    }
}
